/**
 * Holder for the objects to follow
 */
ko.extensions.webos.project = function()
{
    
}
/**
 * Filenames and Defaults
 */
ko.extensions.webos.project.properties = {
    id:{f:"appinfo.json",v:"com.domain.myapp"},
    version:{f:"appinfo.json",v:"1.0.0"},          // NEVER SET IN SCRIPT
    major:{f:"appinfo.json",v:"1"},                // Preparsed, SET THESE
    minor:{f:"appinfo.json",v:"0"},                // Preparsed, SET THESE
    build:{f:"appinfo.json",v:"0"},                // Preparsed, SET THESE
    title:{f:"appinfo.json",v:"My Application"},
    vendor:{f:"appinfo.json",v:"Company"},
    vendorurl:{f:"appinfo.json",v:"http://"},
    main:{f:"appinfo.json",v:"index.html"},
    icon:{f:"appinfo.json",v:"icon.png"},
    smallicon:{f:"appinfo.json",v:"icon32x32.png"},
    type:{f:"appinfo.json",v:"web"},
    theme:{f:"appinfo.json",v:"light"},
    noWindow:{f:"appinfo.json",v:"false"},
    copyright:{f:"appinfo.json",v:"&copy; Copyright 2009 Company"},
    logLevel:{f:"framework_config.json",v:"20"},
    timingEnabled:{f:"framework_config.json",v:"true"},
    logEvents:{f:"framework_config.json",v:"true"},
    debuggingEnabled:{f:"framework_config.json",v:"true"},
    escapeHTMLInTemplates:{f:"framework_config.json",v:"true"}
};
/**
 * Another object holder... must do something with these
 */
ko.extensions.webos.project.list = function()
{
    
}

ko.extensions.webos.project.list.clear = function()
{
    var items = document.getElementById("webosProjectListItems");
    if(items.hasChildNodes())
    {
        while(items.childNodes.length >= 1)
        {
            items.removeChild(items.firstChild);       
        }
    }
}

ko.extensions.webos.project.select = function(id)
{
    var allProjects = ko.projects.manager._projects;
    for(var i in allProjects)
    {
        if(allProjects[i].id == id)
        {
            ko.projects.manager.setCurrentProject(allProjects[i].koIProject);
            break;
        }
    }
}

ko.extensions.webos.project.list.add = function(id, label, icon)
{
    var items = document.getElementById("webosProjectListItems");
    var item = document.createElement("menuitem");
    item.setAttribute("label", label);
    item.setAttribute("value", id);
    if(ko.projects.manager.currentProject.id == id)
        item.setAttribute("style", "font-weight:bold;");
    item.setAttribute("class", "menuitem-iconic");
    item.setAttribute("image", "chrome://webos/skin/" + icon);
    item.setAttribute("oncommand", "ko.extensions.webos.project.select('" + id + "');");
    items.appendChild(item);
}

ko.extensions.webos.project.isWebOS = false;

ko.extensions.webos.project.path = "";

ko.extensions.webos.project.selectedId = "";
ko.extensions.webos.project.selectedLabel = "";
ko.extensions.webos.project.selectedIcon = "";

ko.extensions.webos.project.changed = function(id)
{
    // Add to List in Loop
    var allProjects = ko.projects.manager._projects;
    // On load of editor this is called with 0 projects
    if(id == "" && allProjects.length == 0)
    {
        document.getElementById("webosProjectList").disabled = true;
        document.getElementById("webosProjectListArrow").hidden = true;
        ko.extensions.webos.project.isWebOS = false;
        document.getElementById("webosProjectListLabel").value = "No Projects Opened";
            document.getElementById("webosProjectListImage").src = "chrome://webos/skin/error.png";
        ko.extensions.webos.view.userInterface(false);
    }
    else if(id == null)
    {
        ko.extensions.webos.project.list.clear();
        for(var i in allProjects)
        {
            var icon = "folder_brick.png";
            var file = Components.classes["@mozilla.org/file/local;1"].
                             createInstance(Components.interfaces.nsILocalFile);
            file.initWithPath(allProjects[i].liveDirectory);
            file.append("src");
            file.append("appinfo.json");
            if(file.exists())
                icon = "folder_pre.png";
            ko.extensions.webos.project.list.add(allProjects[i].id,
                                                 allProjects[i].name,
                                                 icon);
        }
    }
    else
    {
        // Clear List
        ko.extensions.webos.project.list.clear();
        ko.extensions.webos.project.path = ko.projects.manager.currentProject.liveDirectory;
        for(var i in allProjects)
        {
            var icon = "folder_brick.png";
            var file = Components.classes["@mozilla.org/file/local;1"].
                             createInstance(Components.interfaces.nsILocalFile);
            file.initWithPath(allProjects[i].liveDirectory);
            file.append("src");
            file.append("appinfo.json");
            if(file.exists())
                icon = "folder_pre.png";
            ko.extensions.webos.project.list.add(allProjects[i].id,
                                                 allProjects[i].name,
                                                 icon);
            if(id == allProjects[i].id)
            {
                ko.extensions.webos.project.selectedId = i;
                ko.extensions.webos.project.selectedName = allProjects[i].name;
                ko.extensions.webos.project.selectedIcon = icon;
                if(icon == "folder_pre.png")
                {
                    ko.extensions.webos.project.isWebOS = true;
                    ko.extensions.webos.view.userInterface(true);
                    ko.extensions.webos.project.updateConfig();
                }
                else
                {
                    ko.extensions.webos.project.isWebOS = false;
                    ko.extensions.webos.view.userInterface(false);
                }
            }
        }
        // Set Selected
        if(id != "")
        {
            var selectedName = ko.extensions.webos.project.selectedName;
            var selectedIcon = "chrome://webos/skin/" + ko.extensions.webos.project.selectedIcon;
            document.getElementById("webosProjectListLabel").value = selectedName;
            document.getElementById("webosProjectListImage").src = selectedIcon;
        }
        else
        {
            ko.extensions.webos.project.isWebOS = false;
            document.getElementById("webosProjectListLabel").value = "No Projects Found";
            document.getElementById("webosProjectListImage").src = "chrome://webos/skin/error.png";
        }
        if(allProjects.length == 1)
        {
            document.getElementById("webosProjectList").disabled = true;
            document.getElementById("webosProjectListArrow").hidden = true;
        }
        else
        {
            document.getElementById("webosProjectList").disabled = false;
            document.getElementById("webosProjectListArrow").hidden = false;
        }
        ko.extensions.webos.jslint.clear();
    }
}

ko.extensions.webos.project.create = function()
{
    // Get current object from form
    var appInfoObject = ko.extensions.webos.json.getObject();
    // Get Path
    var path = document.getElementById("webosNewApplicationPath").value;
    if(path == "")
    {
        document.getElementById("webosNewApplicationPath").disabled = true;
        return false;
    }
    // Create Project File
    var pid = ko.extensions.webos.project.generateId();
    var c = '';
    var name = appInfoObject.title.replace(/[\s'"\-]/g, '');
    c += '<?xml version="1.0" encoding="UTF-8"?>' + "\n";
    c += '<!-- Komodo Project File - DO NOT EDIT -->' + "\n";
    c += '<project id="' + pid + '" kpf_version="4" name="' + name + '.kpf">' + "\n";
    c += '<preference-set idref="' + pid + '">' + "\n";
    c += '  <boolean id="import_live">1</boolean>' + "\n";
    c += '</preference-set>' + "\n";
    c += '</project>';
    
    var proFile = Components.classes["@mozilla.org/file/local;1"].
                        createInstance(Components.interfaces.nsILocalFile);
    proFile.initWithPath(path);
    proFile.append(name + ".kpf");
    
    var foStream = Components.classes["@mozilla.org/network/file-output-stream;1"].
                         createInstance(Components.interfaces.nsIFileOutputStream);
    foStream.init(proFile, 0x02 | 0x08 | 0x20, 0666, 0);
    
    var converter = Components.classes["@mozilla.org/intl/converter-output-stream;1"].
                              createInstance(Components.interfaces.nsIConverterOutputStream);
    converter.init(foStream, "UTF-8", 0, 0);
    converter.writeString(c);
    converter.close();
    // Get path to application folder
    var appFolder = Components.classes["@mozilla.org/file/local;1"].
                        createInstance(Components.interfaces.nsILocalFile);
    appFolder.initWithPath(path);
    appFolder.append("src");
    // Create "src" folder
    if(!appFolder.exists() || !appFolder.isDirectory()) // if it doesn't exist, create
    {
        appFolder.create(Components.interfaces.nsIFile.DIRECTORY_TYPE, 0777);
    }
    document.getElementById("webosNewApplicationCreateProjectButton").disabled = true;
    var oldValue = document.getElementById("webosNewApplicationCreateProjectButton").value;
    document.getElementById("webosNewApplicationCreateProjectButton").value = "...";
    ko.extensions.webos.palm.generateApplication({
        path:appFolder.path,
        appInfo:appInfoObject,
        onSuccess:function(){
            ko.projects.open(proFile.path);
            ko.extensions.webos.project.isWebOS = true;
            ko.extensions.webos.view("main");
            document.getElementById("webosNewApplicationCreateProjectButton").value = oldValue;
            document.getElementById("webosNewApplicationPath").value = "";
        },
        onFailure:function()
        {
            alert("Error: " + this.retval + ", " + this.stdout);
        }
    });
    return true;
};

ko.extensions.webos.project.folder = function()
{
    const nsIFilePicker = Components.interfaces.nsIFilePicker;

    var fp = Components.classes["@mozilla.org/filepicker;1"]
                       .createInstance(nsIFilePicker);
    fp.init(window, "Dialog Title", nsIFilePicker.modeGetFolder);
    fp.appendFilters(nsIFilePicker.filterAll | nsIFilePicker.filterText);
    
    var rv = fp.show();
    if (rv == nsIFilePicker.returnOK || rv == nsIFilePicker.returnReplace)
    {
        var path = fp.file.path;
        var file = Components.classes["@mozilla.org/file/local;1"].
                              createInstance(Components.interfaces.nsILocalFile);
        file.initWithPath(path);
        var entries = file.directoryEntries;
        var files = [];
        while(entries.hasMoreElements())
        {
            var entry = entries.getNext();
            entry.QueryInterface(Components.interfaces.nsIFile);
            files.push(entry);
        }
        if(files.length > 0)
        {
            var err = document.getElementById("webosNewApplicationErrorLabel");
            err.hidden = false;
            err.value = "Select an Empty Folder";
            var errs = document.getElementById("webosNewApplicationErrorSeperator");
            errs.hidden = false;
            var path = document.getElementById("webosNewApplicationPath");
            path.value = "";
            var btn = document.getElementById("webosNewApplicationCreateProjectButton");
            btn.disabled = true;
        }
        else
        {
            var btn = document.getElementById("webosNewApplicationCreateProjectButton");
            btn.disabled = false;
            var err = document.getElementById("webosNewApplicationErrorLabel");
            err.hidden = true;
            err.value = "";
            var errs = document.getElementById("webosNewApplicationErrorSeperator");
            errs.hidden = true;
            var path = document.getElementById("webosNewApplicationPath");
            path.value = file.path;
        }
    }
    else
    {
        var err = document.getElementById("webosNewApplicationErrorLabel");
        err.hidden = false;
        err.value = "Select a Folder";
        var errs = document.getElementById("webosNewApplicationErrorSeperator");
        errs.hidden = false;
        var path = document.getElementById("webosNewApplicationPath");
        path.value = "";
        var btn = document.getElementById("webosNewApplicationCreateProjectButton");
        btn.disabled = true;
    }
};

ko.extensions.webos.project.updateInfo = function(o)
{
    alert("Removed update info function");
};

ko.extensions.webos.project.info = function()
{
    alert("Removed info function");
};

ko.extensions.webos.project.getInfo = function(obj)
{
    ko.extensions.webos.project.getAppInfo({
        onSuccess:function()
        {
            var appInfo = this.json;
            ko.extensions.webos.project.getConfigInfo({
                onSuccess:function()
                {
                    var combinedInfo = this.json;
                    for(var i in appInfo)
                        combinedInfo[i] = appInfo[i];
                    obj.onSuccess.call({json:combinedInfo});
                },
                onFailure:function()
                {
                    obj.onFailure.call({error:this.error});
                }
            });
        },
        onFailure:function()
        {
            obj.onFailure.call({error:this.error});
        }
    });
};

ko.extensions.webos.project.getAppInfo = function(obj)
{
    try
    {
        // Load in appinfo.json
        var appinfoFile = Components.classes["@mozilla.org/file/local;1"].
                                createInstance(Components.interfaces.nsILocalFile);
        appinfoFile.initWithPath(ko.extensions.webos.project.path);
        appinfoFile.append("src");
        appinfoFile.append("appinfo.json");
        var data = "";
        var fstream = Components.classes["@mozilla.org/network/file-input-stream;1"].
                                createInstance(Components.interfaces.nsIFileInputStream);
        var cstream = Components.classes["@mozilla.org/intl/converter-input-stream;1"].
                                createInstance(Components.interfaces.nsIConverterInputStream);
        fstream.init(appinfoFile, -1, 0, 0);
        cstream.init(fstream, "UTF-8", 0, 0);
        let(str = {})
        {
            cstream.readString(-1, str);// read the whole file and put it in str.value
            data = str.value;
        }
        cstream.close(); // Close cstream
        // Parse and Return appinfo.json
        try
        {
            var nativeJSON = Components.classes["@mozilla.org/dom/json;1"].createInstance(Components.interfaces.nsIJSON); 
            obj.onSuccess.call({json:nativeJSON.decode(data), text:data});
        }
        catch(err)
        {
            obj.onFailure.call({error:"Error: Failed to parse appinfo.json", errorCode:2});
        }
    }
    catch(err)
    {
        obj.onFailure.call({error:"Error: Failed to load appinfo.json", errorCode:1});
    }
};

ko.extensions.webos.project.setAppInfo = function(obj)
{
    ko.extensions.webos.project.getAppInfo({
        onSuccess:function()
        {
            try
            {
                var json = this.json;
                for(var i in obj.appInfo)
                    json[i] = obj.appInfo[i];
                var str = ko.extensions.webos.json.toString(json);
                var appinfoFile = Components.classes["@mozilla.org/file/local;1"].
                                createInstance(Components.interfaces.nsILocalFile);
                appinfoFile.initWithPath(ko.extensions.webos.project.path);
                appinfoFile.append("src");
                appinfoFile.append("appinfo.json");
                var foStream = Components.classes["@mozilla.org/network/file-output-stream;1"].
                                     createInstance(Components.interfaces.nsIFileOutputStream);
                foStream.init(appinfoFile, 0x02 | 0x08 | 0x20, 0666, 0);
                
                var converter = Components.classes["@mozilla.org/intl/converter-output-stream;1"].
                                          createInstance(Components.interfaces.nsIConverterOutputStream);
                converter.init(foStream, "UTF-8", 0, 0);
                converter.writeString(str);
                converter.close();
                obj.onSuccess.call({text:str,json:json});
            }
            catch(err)
            {
                obj.onSuccess.call({error:"Error: Failed to save appinfo.json",errorCode:1});
            }
        },
        onFailure:function()
        {
            alert(this.error);
        }
    });
};


ko.extensions.webos.project.addScene = function()
{
    var name = document.getElementById("webosAddSceneText").value;
    ko.extensions.webos.palm.newScene({
        name:name,
        onSuccess:function()
        {
            ko.extensions.webos.view("addscene");
        },
        onFailure:function()
        {
            alert("Error: Failed to create new scene");
        }
    });
};

ko.extensions.webos.project.addSceneCheck = function()
{
    var t = document.getElementById("webosAddSceneText").value;
    if(t.match(/^[\w_-]+$/))
    {
        document.getElementById("webosAddSceneText").style.color = "#000";
        document.getElementById("webosAddSceneButton").disabled = false;
        document.getElementById("webosAddSceneButton").setAttribute("image", "chrome://webos/skin/page_white_add.png");
    }
    else
    {
        document.getElementById("webosAddSceneText").style.color = "#900";
        document.getElementById("webosAddSceneButton").disabled = true;
        document.getElementById("webosAddSceneButton").setAttribute("image", "chrome://webos/skin/page_white_add_disabled.png");
    }
};

ko.extensions.webos.project.getConfigInfo = function(obj)
{
    try
    {
        // Load in framework_config.json
        var configFile = Components.classes["@mozilla.org/file/local;1"].
                                createInstance(Components.interfaces.nsILocalFile);
        configFile.initWithPath(ko.extensions.webos.project.path);
        configFile.append("src");
        configFile.append("framework_config.json");
        var data = "";
        var fstream = Components.classes["@mozilla.org/network/file-input-stream;1"].
                                createInstance(Components.interfaces.nsIFileInputStream);
        var cstream = Components.classes["@mozilla.org/intl/converter-input-stream;1"].
                                createInstance(Components.interfaces.nsIConverterInputStream);
        fstream.init(configFile, -1, 0, 0);
        cstream.init(fstream, "UTF-8", 0, 0);
        let(str = {})
        {
            cstream.readString(-1, str);// read the whole file and put it in str.value
            data = str.value;
        }
        cstream.close(); // Close cstream
        // Parse and Return framework_config.json
        try
        {
            var nativeJSON = Components.classes["@mozilla.org/dom/json;1"].createInstance(Components.interfaces.nsIJSON); 
            obj.onSuccess.call({json:nativeJSON.decode(data), text:data});
        }
        catch(err)
        {
            obj.onFailure.call({error:"Error: Failed to parse framework_config.json", errorCode:2});
        }
    }
    catch(err)
    {
        obj.onFailure.call({error:"Error: Failed to load framework_config.json", errorCode:1});
    }
};

ko.extensions.webos.project.setConfigInfo = function(obj)
{
    if(typeof(obj.overwrite) == undefined)
        obj.overwrite = false;
    var save = function(obj)
    {
        var str = ko.extensions.webos.json.toString(obj.config);
        var configFile = Components.classes["@mozilla.org/file/local;1"].
                        createInstance(Components.interfaces.nsILocalFile);
        configFile.initWithPath(ko.extensions.webos.project.path);
        configFile.append("src");
        configFile.append("framework_config.json");
        var foStream = Components.classes["@mozilla.org/network/file-output-stream;1"].
                             createInstance(Components.interfaces.nsIFileOutputStream);
        foStream.init(configFile, 0x02 | 0x08 | 0x20, 0666, 0);
        
        var converter = Components.classes["@mozilla.org/intl/converter-output-stream;1"].
                                  createInstance(Components.interfaces.nsIConverterOutputStream);
        converter.init(foStream, "UTF-8", 0, 0);
        converter.writeString(str);
        converter.close();
        obj.onSuccess.call({json:obj.config, text:str});
    };
    if(obj.overwrite)
    {
        save(obj);
    }
    else
    {
        ko.extensions.webos.project.getConfigInfo({
            onSuccess:function()
            {
                try
                {
                    for(var i in obj.config)
                        this.json[i] = obj.config[i];
                    obj.config = this.json;
                    save(obj);
                }
                catch(err)
                {
                    obj.onFailure.call({error:"Error: Failed to save framework_config.json"});
                }
            },
            onFailure:function()
            {
                alert(this.error);
            }
        });
    }
};

ko.extensions.webos.project.updateConfig = function()
{
    ko.extensions.webos.project.getConfigInfo({
        onSuccess:function()
        {
            var log = "Off";
            if(this.json.logLevel >= 20)
                log = "20";
            else if(this.json.logLevel >= 10)
                log = "10";
            else if(this.json.logLevel >= 0
                    && this.json.debuggingEnabled == true)
                log = "0";
            else
                log = "Off";
            if(log == "Off")
            {
                document.getElementById("webosDebugButton").disabled = true;
                document.getElementById("webosDebugButton").
                    setAttribute("image", "chrome://webos/skin/bug_arrowleft_disabled.png");
            }
            var a = ["0", "10", "20", "Off"];
            for(var i in a)
                document.getElementById("webosConfigLog" + a[i]).setAttribute("checked", "false");
            // Toggles set to true or false
            document.getElementById("webosConfigLog" + log).setAttribute("checked", "true");
            var b = this.json.escapeHTMLInTemplates == true ? "true" : "false";
            document.getElementById("webosConfigEscape").setAttribute("checked", b);
            b = this.json.timingEnabled == true ? "true" : "false";
            document.getElementById("webosConfigTiming").setAttribute("checked", b);
            b = this.json.logEvents == true ? "true" : "false";
            document.getElementById("webosConfigEvents").setAttribute("checked", b);
            // Drop down icon
            document.getElementById("webosConfigImage").src = 
                "chrome://webos/skin/cog_" + log.toLowerCase() + "_arrowdown.png";
            document.getElementById("webosConfigLogRepair").hidden = true;
            document.getElementById("webosConfigLog20").hidden = false;
            document.getElementById("webosConfigLog10").hidden = false;
            document.getElementById("webosConfigLog0").hidden = false;
            document.getElementById("webosConfigLogOff").hidden = false;
            document.getElementById("webosConfigSeperator").hidden = false;
            document.getElementById("webosConfigEscape").hidden = false;
            document.getElementById("webosConfigTiming").hidden = false;
            document.getElementById("webosConfigEvents").hidden = false;
            var t = document.getElementById("webosConfigLogLevelTooltip").value;
            document.getElementById("webosConfigButton").setAttribute("tooltiptext", t);
        },
        onFailure:function()
        {
            document.getElementById("webosConfigImage").src = 
                "chrome://webos/skin/cog_error_arrowdown.png";
            document.getElementById("webosConfigLogRepair").hidden = false;
            document.getElementById("webosConfigLog20").hidden = true;
            document.getElementById("webosConfigLog10").hidden = true;
            document.getElementById("webosConfigLog0").hidden = true;
            document.getElementById("webosConfigLogOff").hidden = true;
            document.getElementById("webosConfigSeperator").hidden = true;
            document.getElementById("webosConfigEscape").hidden = true;
            document.getElementById("webosConfigTiming").hidden = true;
            document.getElementById("webosConfigEvents").hidden = true;
            var t = document.getElementById("webosConfigLogLevelErrorTooltip").value;
            document.getElementById("webosConfigButton").setAttribute("tooltiptext", t);
            document.getElementById("webosDebugButton").disabled = true;
            document.getElementById("webosDebugButton").
                setAttribute("image", "chrome://webos/skin/bug_arrowleft_disabled.png");
        }
    });
};

ko.extensions.webos.project.repairLog = function()
{
    ko.extensions.webos.project.setConfigInfo({
        overwrite:true,
        config:{
            "logLevel": 20,
            "debuggingEnabled": true,
            "timingEnabled": false,
            "logEvents": false,
            "escapeHTMLInTemplates" : true
        },
        onSuccess:function()
        {
            // File was repaired.
        },
        onFailure:function()
        {
            alert(this.error);
        }
    });
};

ko.extensions.webos.project.updateEditInfoField = function()
{
    alert("Update App Info Field");
};

ko.extensions.webos.project.updateVersionField = function()
{
    var appInfoObject = ko.extensions.webos.project.getAppInfo({
        onSuccess:function()
        {
            // Load Content
            var v = ko.extensions.webos.json.versionToObject(this.json.version);
            document.getElementById("webosEditInfoMajorTop").value = v.major;
            document.getElementById("webosEditInfoMinorTop").value = v.minor;
            document.getElementById("webosEditInfoBuildTop").value = v.build;
            // Update View
            var tooltip = document.getElementById("webosEditInfoTooltip").value;
            var btn = document.getElementById("webosEditInfoViewButton");
            btn.image = "chrome://webos/skin/page_white_text.png";
            btn.setAttribute("tooltiptext", tooltip);
            document.getElementById("webosEditInfoMajorTop").hidden = false;
            document.getElementById("webosEditInfoMinorTop").hidden = false;
            document.getElementById("webosEditInfoBuildTop").hidden = false;
        },
        onFailure:function()
        {
            // Hide and show error
            var tooltip = document.getElementById("webosEditInfoErrorTooltip").value;
            var btn = document.getElementById("webosEditInfoViewButton");
            btn.image = "chrome://webos/skin/page_white_text_error.png";
            btn.setAttribute("tooltiptext", tooltip);
            document.getElementById("webosEditInfoMajorTop").hidden = true;
            document.getElementById("webosEditInfoMinorTop").hidden = true;
            document.getElementById("webosEditInfoBuildTop").hidden = true;
        }
    });
}

ko.extensions.webos.project.updateVersion = function()
{
    var version = document.getElementById("webosEditInfoMajorTop").value
        + "." + document.getElementById("webosEditInfoMinorTop").value
        + "." + document.getElementById("webosEditInfoBuildTop").value;
    ko.extensions.webos.project.setAppInfo({
        appInfo:{
            version:version
        },
        onSuccess:function()
        {
            // Updated
        },
        onFailure:function()
        {
            alert(this.error);
        }
    });
    document.getElementById("webosEditInfoMajor").value =
        document.getElementById("webosEditInfoMajorTop").value;
    document.getElementById("webosEditInfoMinor").value =
        document.getElementById("webosEditInfoMinorTop").value;
    document.getElementById("webosEditInfoBuild").value =
        document.getElementById("webosEditInfoBuildTop").value;
}

ko.extensions.webos.project.updateLog = function(level)
{
    switch(level)
    {
        case "20":
            ko.extensions.webos.project.setConfigInfo({
                config:{
                    "logLevel":20,
                    "debuggingEnabled":true
                },
                onSuccess:function(){},onFailure:function(){alert(this.error);}
            });
            // Enable Debug Options
            document.getElementById("webosDebug").style.display = "none";
            document.getElementById("webosDebugButton").setAttribute("image", "chrome://webos/skin/bug_arrowleft.png");
            document.getElementById("webosDebugButton").disabled = false;
            break;
        case "10":
            ko.extensions.webos.project.setConfigInfo({
                config:{
                    "logLevel":10,
                    "debuggingEnabled":true
                },
                onSuccess:function(){},onFailure:function(){alert(this.error);}
            });
            // Enable Debug Options
            document.getElementById("webosDebug").style.display = "none";
            document.getElementById("webosDebugButton").setAttribute("image", "chrome://webos/skin/bug_arrowleft.png");
            document.getElementById("webosDebugButton").disabled = false;
            break;
        case "0":
            ko.extensions.webos.project.setConfigInfo({
                config:{
                    "logLevel":0,
                    "debuggingEnabled":true
                },
                onSuccess:function(){},onFailure:function(){alert(this.error);}
            });
            // Enable Debug Options
            document.getElementById("webosDebug").style.display = "none";
            document.getElementById("webosDebugButton").setAttribute("image", "chrome://webos/skin/bug_arrowleft.png");
            document.getElementById("webosDebugButton").disabled = false;
            break;
        case "Off":
            ko.extensions.webos.project.setConfigInfo({
                config:{
                    "logLevel":0,
                    "debuggingEnabled":false
                },
                onSuccess:function(){},onFailure:function(){alert(this.error);}
            });
            // Disable Debug Options
            document.getElementById("webosDebug").style.display = "none";
            document.getElementById("webosDebugButton").setAttribute("image", "chrome://webos/skin/bug_arrowleft_disabled.png");
            document.getElementById("webosDebugButton").disabled = true;
            break;
    }
    document.getElementById("webosConfigImage").src = 
        "chrome://webos/skin/cog_" + level.toLowerCase() + "_arrowdown.png";
};

ko.extensions.webos.project.updateEscape = function()
{
    ko.extensions.webos.project.getConfigInfo({
        onSuccess:function()
        {
            ko.extensions.webos.project.setConfigInfo({
                config:{
                    "escapeHTMLInTemplates":!this.json.escapeHTMLInTemplates
                },
                onSuccess:function(){},onFailure:function(){alert(this.error);}
            });
        },
        onFailure:function()
        {
            alert(this.error);
        }
    });
};

ko.extensions.webos.project.updateTiming = function()
{
    ko.extensions.webos.project.getConfigInfo({
        onSuccess:function()
        {
            ko.extensions.webos.project.setConfigInfo({
                config:{
                    "timingEnabled":!this.json.timingEnabled
                },
                onSuccess:function(){},onFailure:function(){alert(this.error);}
            });
        },
        onFailure:function()
        {
            alert(this.error);
        }
    });
};

ko.extensions.webos.project.updateEvents = function()
{
    ko.extensions.webos.project.getConfigInfo({
        onSuccess:function()
        {
            ko.extensions.webos.project.setConfigInfo({
                config:{
                    "logEvents":!this.json.logEvents
                },
                onSuccess:function(){},onFailure:function(){alert(this.error);}
            });
        },
        onFailure:function()
        {
            alert(this.error);
        }
    });
};

ko.extensions.webos.project.generateId = function()
{
    return ko.extensions.webos.project.uuid();
};

// http://www.broofa.com/blog/2008/09/javascript-uuid-function/
ko.extensions.webos.project.uuid = function(len, radix)
{
    var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split(''); 
    var chars = CHARS, uuid = [], rnd = Math.random;
    radix = radix || chars.length;
    
    if (len) {
        // Compact form
        for (var i = 0; i < len; i++) uuid[i] = chars[0 | rnd()*radix];
    } else {
        // rfc4122, version 4 form
        var r;
        
        // rfc4122 requires these characters
        uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
        uuid[14] = '4';
        
        // Fill in random data.  At i==19 set the high bits of clock sequence as
        // per rfc4122, sec. 4.1.5
        for (var i = 0; i < 36; i++) {
            if (!uuid[i]) {
                r = 0 | rnd()*16;
                uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r & 0xf];
            }
        }
    }
    return uuid.join('');
};

ko.extensions.webos.project.updateAppInfoTabIfFound = function(data)
{
    var views = ko.views.manager.topView.getDocumentViewList(true);
    var ios = Components.classes["@mozilla.org/network/io-service;1"].
                         getService(Components.interfaces.nsIIOService);
    var appInfo = Components.classes["@mozilla.org/file/local;1"].
                     createInstance(Components.interfaces.nsILocalFile);
    appInfo.initWithPath(ko.extensions.webos.project.path);
    appInfo.append("src");
    appInfo.append("appinfo.json");
    for(var i in views)
    {
        var path = ios.newURI(views[i].getURI(), null, null).
                       QueryInterface(Components.interfaces.nsIFileURL).file.path;
        if(path == appInfo.path)
        {
            views[i].scimoz.selectAll();
            views[i].scimoz.replaceSel(data);
        }
    }
};

ko.extensions.webos.project.updateFrameworkConfigTabIfFound = function(data)
{
    var views = ko.views.manager.topView.getDocumentViewList(true);
    var ios = Components.classes["@mozilla.org/network/io-service;1"].
                         getService(Components.interfaces.nsIIOService);
    var frameworkConfig = Components.classes["@mozilla.org/file/local;1"].
                     createInstance(Components.interfaces.nsILocalFile);
    frameworkConfig.initWithPath(ko.extensions.webos.project.path);
    frameworkConfig.append("src");
    frameworkConfig.append("framework_config.json");
    for(var i in views)
    {
        var path = ios.newURI(views[i].getURI(), null, null).
                       QueryInterface(Components.interfaces.nsIFileURL).file.path;
        if(path == frameworkConfig.path)
        {
            views[i].scimoz.selectAll();
            views[i].scimoz.replaceSel(data);
        }
    }
};